package com.liao.badminton.handler.security;


import com.liao.badminton.code.ProjectException;
import com.liao.badminton.code.RespCodeMessage;
import com.liao.badminton.code.ResponseRest;
import com.liao.badminton.redis.RedisEnum;
import com.liao.badminton.redis.RedisUtil;
import com.liao.badminton.code.util.JwtTokenUtils;
import com.liao.badminton.code.util.ResponseUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * author liaocheng
 * description : 退出登录处理
 * DATE: 2021/2/22
 */
@Component
@Log4j2
public class MyLogoutHandler implements LogoutHandler {
    @Override
    public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {

        String tokenHeader = httpServletRequest.getHeader(JwtTokenUtils.TOKEN_HEADER);
        if (tokenHeader == null || !tokenHeader.startsWith(JwtTokenUtils.TOKEN_PREFIX)) {
            ProjectException.newException(RespCodeMessage.SECURITY_ACCOUNT_LOGOUT_FAIL, "用户未登录");
        }

        try {
            String token = tokenHeader.replace(JwtTokenUtils.TOKEN_PREFIX, "");
            String username = JwtTokenUtils.getUsername(token);
            RedisUtil.toDelete(RedisEnum.USER_LOGIN_NAME, username);
            JwtTokenUtils.delToken(token);
        } catch (Exception e) {
            log.info("清除token异常..{}", e);
        }
        ResponseRest result = ResponseRest.suc("logout");
        ResponseUtils.out(httpServletResponse, result);
    }
}
